//
//  IMUtilsManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/6/23.
//

#import "IMUtilsManager.h"

static NSString * const kIMSDKVersion = @"1.0.0";
static NSDictionary *globalConfig = nil;

@implementation IMUtilsManager

+ (void)initializeUtils {
    // 根据环境自动选择配置
    IMLogConfig *logConfig;
    
#ifdef DEBUG
    logConfig = [IMLogConfig debugConfig];
#else
    logConfig = [IMLogConfig releaseConfig];
#endif
    
    // 设置日志目录到Documents/IMLogs
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths firstObject];
    logConfig.logDirectory = [documentsPath stringByAppendingPathComponent:@"IMLogs"];
    
    // 初始化日志系统
    [IMLogUtils initWithConfig:logConfig];
    
    // 日志系统初始化完成后再记录日志
#ifdef DEBUG
    [IMLogUtils info:IMLogTagSDKInit format:@"使用Debug环境配置"];
#else
    [IMLogUtils info:IMLogTagSDKInit format:@"使用Release环境配置"];
#endif
    
    // 初始化网络工具
    IMNetworkConfig *networkConfig;
#ifdef DEBUG
    networkConfig = [IMNetworkConfig debugConfig];
#else
    networkConfig = [IMNetworkConfig releaseConfig];
#endif
    [IMNetworkUtils initWithConfig:networkConfig];
    
    // 记录SDK初始化信息
    [self logSDKInitInfo];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"IMUtilsManager 初始化完成"];
}

+ (void)initializeWithCustomConfig:(IMLogConfig *)logConfig {
    if (!logConfig) {
        [self initializeUtils];
        return;
    }
    
    // 使用自定义配置初始化日志系统
    [IMLogUtils initWithConfig:logConfig];
    
    // 记录SDK初始化信息
    [self logSDKInitInfo];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"IMUtilsManager 使用自定义配置初始化完成"];
}

+ (NSString *)sdkVersion {
    return kIMSDKVersion;
}

+ (void)setGlobalConfig:(NSDictionary *)config {
    globalConfig = [config copy];
    [IMLogUtils info:IMLogTagSDKInit format:@"全局配置已更新: %@", config];
}

+ (NSDictionary *)globalConfig {
    return globalConfig;
}

+ (id)configValueForKey:(NSString *)key {
    return globalConfig[key];
}

+ (void)setConfigValue:(id)value forKey:(NSString *)key {
    if (!globalConfig) {
        globalConfig = @{};
    }
    
    NSMutableDictionary *mutableConfig = [globalConfig mutableCopy];
    if (value) {
        mutableConfig[key] = value;
    } else {
        [mutableConfig removeObjectForKey:key];
    }
    globalConfig = [mutableConfig copy];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"配置项 %@ 已更新为: %@", key, value];
}

#pragma mark - SDK Information

+ (void)logSDKInitInfo {
    // 记录SDK基本信息
    [IMLogUtils info:IMLogTagSDKInit format:@"========== DualMediationSDK 初始化 =========="];
    [IMLogUtils info:IMLogTagSDKInit format:@"SDK版本: %@", [self sdkVersion]];
    [IMLogUtils info:IMLogTagSDKInit format:@"构建时间: %s %s", __DATE__, __TIME__];
    
    // 记录设备信息
    [self logDeviceInfo];
    
    // 记录应用信息
    [self logAppInfo];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"============================================"];
}

+ (void)logDeviceInfo {
    NSDictionary *deviceInfo = [IMDeviceUtils deviceInfo];
    [IMLogUtils info:IMLogTagSDKInit format:@"设备信息: %@", deviceInfo];
}

+ (void)logAppInfo {
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSDictionary *infoDictionary = [mainBundle infoDictionary];
    
    NSString *appName = infoDictionary[@"CFBundleName"] ?: @"Unknown";
    NSString *appVersion = infoDictionary[@"CFBundleShortVersionString"] ?: @"Unknown";
    NSString *buildNumber = infoDictionary[@"CFBundleVersion"] ?: @"Unknown";
    NSString *bundleId = infoDictionary[@"CFBundleIdentifier"] ?: @"Unknown";
    
    [IMLogUtils info:IMLogTagSDKInit format:@"应用信息:"];
    [IMLogUtils info:IMLogTagSDKInit format:@"  应用名称: %@", appName];
    [IMLogUtils info:IMLogTagSDKInit format:@"  应用版本: %@(%@)", appVersion, buildNumber];
    [IMLogUtils info:IMLogTagSDKInit format:@"  Bundle ID: %@", bundleId];
}

#pragma mark - Utility Methods

+ (NSString *)formatFileSize:(NSUInteger)bytes {
    if (bytes < 1024) {
        return [NSString stringWithFormat:@"%lu B", (unsigned long)bytes];
    } else if (bytes < 1024 * 1024) {
        return [NSString stringWithFormat:@"%.1f KB", bytes / 1024.0];
    } else if (bytes < 1024 * 1024 * 1024) {
        return [NSString stringWithFormat:@"%.1f MB", bytes / (1024.0 * 1024.0)];
    } else {
        return [NSString stringWithFormat:@"%.1f GB", bytes / (1024.0 * 1024.0 * 1024.0)];
    }
}

+ (NSString *)formatDuration:(NSTimeInterval)duration {
    if (duration < 1.0) {
        return [NSString stringWithFormat:@"%.0f ms", duration * 1000];
    } else if (duration < 60.0) {
        return [NSString stringWithFormat:@"%.1f s", duration];
    } else if (duration < 3600.0) {
        return [NSString stringWithFormat:@"%.1f min", duration / 60.0];
    } else {
        return [NSString stringWithFormat:@"%.1f h", duration / 3600.0];
    }
}

+ (NSString *)currentTimestamp {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    return [formatter stringFromDate:[NSDate date]];
}

+ (NSString *)iso8601Timestamp {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    return [formatter stringFromDate:[NSDate date]];
}

#pragma mark - Debug Methods

+ (void)printSystemInfo {
    [IMLogUtils info:IMLogTagGeneral format:@"========== 系统信息 =========="];
    
    // 设备信息
    NSDictionary *deviceInfo = [IMDeviceUtils deviceInfo];
    for (NSString *key in deviceInfo) {
        [IMLogUtils info:IMLogTagGeneral format:@"%@: %@", key, deviceInfo[key]];
    }
    
    // 内存信息
    NSUInteger totalMemory = [IMDeviceUtils totalMemory];
    NSUInteger availableMemory = [IMDeviceUtils availableMemory];
    [IMLogUtils info:IMLogTagGeneral format:@"总内存: %@", [self formatFileSize:totalMemory]];
    [IMLogUtils info:IMLogTagGeneral format:@"可用内存: %@", [self formatFileSize:availableMemory]];
    [IMLogUtils info:IMLogTagGeneral format:@"内存使用率: %.1f%%", (totalMemory - availableMemory) * 100.0 / totalMemory];
    
    // 日志信息
    NSArray *logFiles = [IMLogUtils allLogFilePaths];
    NSUInteger totalLogSize = [IMLogUtils totalLogFileSize];
    [IMLogUtils info:IMLogTagGeneral format:@"日志文件数量: %lu", (unsigned long)logFiles.count];
    [IMLogUtils info:IMLogTagGeneral format:@"日志文件总大小: %@", [self formatFileSize:totalLogSize]];
    
    [IMLogUtils info:IMLogTagGeneral format:@"============================"];
}

+ (void)clearAllCaches {
    [IMLogUtils info:IMLogTagGeneral format:@"开始清理缓存..."];
    
    // 清理日志文件
    [IMLogUtils cleanLogFiles];
    
    // 清理NSURLCache
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    // 清理用户默认设置中的临时数据
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"IMTempData"];
    [defaults synchronize];
    
    [IMLogUtils info:IMLogTagGeneral format:@"缓存清理完成"];
}

+ (NSDictionary *)gatherDiagnosticInfo {
    NSMutableDictionary *diagnosticInfo = [NSMutableDictionary dictionary];
    
    // SDK信息
    diagnosticInfo[@"sdk_info"] = @{
        @"version": [self sdkVersion],
        @"build_date": [NSString stringWithFormat:@"%s", __DATE__],
        @"build_time": [NSString stringWithFormat:@"%s", __TIME__]
    };
    
    // 设备信息
    diagnosticInfo[@"device_info"] = [IMDeviceUtils deviceInfo];
    
    // 应用信息
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSDictionary *infoDictionary = [mainBundle infoDictionary];
    diagnosticInfo[@"app_info"] = @{
        @"name": infoDictionary[@"CFBundleName"] ?: @"Unknown",
        @"version": infoDictionary[@"CFBundleShortVersionString"] ?: @"Unknown",
        @"build": infoDictionary[@"CFBundleVersion"] ?: @"Unknown",
        @"bundle_id": infoDictionary[@"CFBundleIdentifier"] ?: @"Unknown"
    };
    
    // 内存信息
    diagnosticInfo[@"memory_info"] = @{
        @"total": @([IMDeviceUtils totalMemory]),
        @"available": @([IMDeviceUtils availableMemory]),
        @"used_percentage": @(([IMDeviceUtils totalMemory] - [IMDeviceUtils availableMemory]) * 100.0 / [IMDeviceUtils totalMemory])
    };
    
    // 日志信息
    NSArray *logFiles = [IMLogUtils allLogFilePaths];
    diagnosticInfo[@"log_info"] = @{
        @"file_count": @(logFiles.count),
        @"total_size": @([IMLogUtils totalLogFileSize]),
        @"current_level": @([IMLogUtils currentLogLevel])
    };
    
    // 配置信息
    if (globalConfig) {
        diagnosticInfo[@"global_config"] = globalConfig;
    }
    
    // 时间戳
    diagnosticInfo[@"timestamp"] = [self iso8601Timestamp];
    
    return [diagnosticInfo copy];
}

+ (NSString *)exportDiagnosticInfo {
    NSDictionary *diagnosticInfo = [self gatherDiagnosticInfo];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:diagnosticInfo 
                                                        options:NSJSONWritingPrettyPrinted 
                                                          error:&error];
    
    if (error) {
        [IMLogUtils error:IMLogTagGeneral format:@"导出诊断信息失败: %@", error.localizedDescription];
        return nil;
    }
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    [IMLogUtils info:IMLogTagGeneral format:@"诊断信息导出成功，大小: %lu 字符", (unsigned long)jsonString.length];
    
    return jsonString;
}

+ (BOOL)saveDiagnosticInfoToFile:(NSString *)filePath {
    NSString *diagnosticInfo = [self exportDiagnosticInfo];
    if (!diagnosticInfo) {
        return NO;
    }
    
    NSError *error;
    BOOL success = [diagnosticInfo writeToFile:filePath 
                                    atomically:YES 
                                      encoding:NSUTF8StringEncoding 
                                         error:&error];
    
    if (success) {
        [IMLogUtils info:IMLogTagGeneral format:@"诊断信息已保存到: %@", filePath];
    } else {
        [IMLogUtils error:IMLogTagGeneral format:@"保存诊断信息失败: %@", error.localizedDescription];
    }
    
    return success;
}

@end